require 'digest/sha1'

class Commentableship < ActiveRecord::Base
	belongs_to :commentable, :polymorphic => true
	belongs_to :user
	before_create :generate_ident
	
	#If there is no unread comments for spec user and item(photo, article and etc) creates new commentable
	#else make unread commentable last visit to now
	def self.add_last_visit(user_id, commentable_type, commentable_id)
		commentable = self.find(:first, :conditions => ["user_id = ? AND commentable_type = ? and commentable_id = ?", user_id, commentable_type, commentable_id])
		if !commentable.nil?
			commentable.last_visit = Time.now
		else
			commentable = Commentableship.new()
			commentable.user_id = user_id
			commentable.commentable_type = commentable_type
			commentable.commentable_id = commentable_id
			commentable.last_visit = Time.now
		end
		commentable.save
	end
        
    def self.get_last_visit(user_id, commentable_type, commentable_id)
      commentable = self.find(:first, :conditions => ["user_id = ? AND commentable_type = ? and commentable_id = ?", user_id, commentable_type, commentable_id])
      if !commentable.nil?
          commentable.last_visit = Time.now
      else
          commentable = Commentableship.new()
          commentable.user_id = user_id
          commentable.commentable_type = commentable_type
          commentable.commentable_id = commentable_id
          commentable.last_visit = Time.now
      end
      commentable
	end
	
	def self.update_last_visit(user_id, commentable_type, commentable_id)
		commentable = self.find(:first, :conditions => ["user_id = ? AND commentable_type = ? and commentable_id = ?", user_id, commentable_type, commentable_id])
		if !commentable.nil?
			commentable.last_visit = Time.now
			commentable.save
		end
	end
    
    def self.find_commentableships_for(user)
		commentableships = Commentableship.find(:all, 
						:select => " commentableships.id, commentableships.commentable_id, commentableships.commentable_type, " +
   								   "commentableships.user_id, last_visit, COUNT(comments.id) as comments_count, " +
   								   "MAX(comments.created_at) as max_created_at",
   					    :joins => "left JOIN comments on 
   					                commentableships.commentable_id = comments.commentable_id and 
   					                commentableships.commentable_type = comments.commentable_type and 
   					                commentableships.last_visit < comments.created_at and 
   					                comments.user_id <> #{user.id}",
                        :group => "commentableships.commentable_id, commentableships.commentable_type, commentableships.user_id",
                        :conditions => ["commentableships.user_id = ? and commentableships.is_watching = 1", user.id],
						:order => "max_created_at desc")        	
    end 
    
	def generate_ident
		self.ident = Digest::SHA1.hexdigest("--#{Time.now}--#{self.commentable_type}--#{self.commentable_id}")[0..10]
	end 	 
end
